import 'dart:convert';

import 'package:bruno/bruno.dart';
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:intl/intl.dart';
import 'package:miuu_note_app/dao/todo_dao.dart';
import 'package:miuu_note_app/model/todo_entity.dart';

import '../constant/todo_enum.dart';
import '../generated/l10n.dart';
import '../model/msg_entity.dart';

class TodoEdit extends StatefulWidget {
  const TodoEdit({super.key});
  @override
  State<TodoEdit> createState() => _TodoEditState();
}

class _TodoEditState extends State<TodoEdit> {
  TodoModel todoModel = TodoModel();

  final TextEditingController _titleController = TextEditingController()
    ..text = '';
  final TextEditingController _contentController = TextEditingController()
    ..text = '';

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      var arguments = ModalRoute.of(context)?.settings.arguments;
      if (arguments != null) {
        setState(() {
          todoModel = TodoModel.fromJson(jsonDecode(arguments.toString()));
          _titleController.text = todoModel.title!;
          _contentController.text = todoModel.content!;
        });
      }
    });
  }

  @override
  void dispose() {
    //将要销毁的方法或数据放在这里
    super.dispose();

    _titleController.dispose();
    _contentController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      localizationsDelegates: [
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
        BrnLocalizationDelegate.delegate,
      ],
      // 应用支持的语言列表
      supportedLocales: S.delegate.supportedLocales,
      color: Colors.blue,
      home: Scaffold(
          body: ListView(
        children: [
          BrnNormalFormGroup(
            title: todoModel.todoId == null ? "新增待办" : "编辑待办",
            children: [
              BrnRadioInputFormItem(
                title: "类型",
                options: const [
                  "工作",
                  "生活",
                ],
                value: SnippetType.getLabel(todoModel.type ?? '1'),
                onChanged: (oldValue, newValue) {
                  todoModel.type = SnippetType.getValue(newValue!);
                  // BrnToast.show(
                  //     "点击触发回调${oldValue}_${newValue}_onChanged", context);
                },
              ),
              BrnTextInputFormItem(
                controller: _titleController,
                title: "标题",
                hint: "请输入",
                isRequire: true,
                onChanged: (newValue) {
                  todoModel.title = newValue;
                },
              ),
              BrnRadioInputFormItem(
                title: "等级",
                options: const [
                  "一般",
                  "优先",
                  "紧急",
                ],
                value: Level.getLabel(todoModel.level ?? 0),
                onChanged: (oldValue, newValue) {
                  todoModel.level = Level.getValue(newValue!);
                },
              ),
              BrnTextSelectFormItem(
                title: "待办日期",
                label: '请选择',
                value: todoModel.todoDate,
                isRequire: true,
                onTap: () {
                  BrnDatePicker.showDatePicker(context,
                      maxDateTime: DateTime.parse('2083-01-15 00:00:00'),
                      minDateTime: DateTime.parse('2024-01-01 00:00:00'),
                      initialDateTime: todoModel.todoDate != ''
                          ? DateTime.parse(todoModel.todoDate ?? '2024-01-01')
                          : DateTime.now(),
                      // 支持DateTimePickerMode.date、DateTimePickerMode.datetime、DateTimePickerMode.time
                      pickerMode: BrnDateTimePickerMode.date,
                      pickerTitleConfig: BrnPickerTitleConfig.Default,
                      dateFormat: 'yyyy年,MM月,dd日', onConfirm: (dateTime, list) {
                    setState(() {
                      todoModel.todoDate =
                          DateFormat("yyyy-MM-dd").format(dateTime);
                      // BrnToast.show("onConfirm:  $dateTime   $list", context);
                    });
                  });
                },
              ),
              BrnTextBlockInputFormItem(
                controller: _contentController,
                title: "内容",
                hint: "请输入内容",
                minLines: 1,
                maxLines: 5,
                onChanged: (newValue) {
                  setState(() {
                    todoModel.content = newValue;
                    print(jsonEncode(todoModel));
                  });
                },
              ),
              BrnBottomButtonPanel(
                mainButtonName: '提交',
                mainButtonOnTap: () {
                  _saveOrUpdateTodo(todoModel.toJson()).then((value) {
                    BrnToast.show(
                        value!.msgModel.msg ?? '操作异常，请联系管理员', context);
                    if (value.msgModel.code == 200) {
                      Navigator.pop(context, value.msgModel);
                    }
                  });
                },
              )
            ],
          ),
        ],
      )),
    );
  }

  Future<MsgEntity?> _saveOrUpdateTodo(Map<String, dynamic> map) async {
    return await TodoSaveOrUpdateDao.fetch(map);
  }
}
